<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>商品信息搜索系统</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        :root {
            --primary-color: #3498db;
            --secondary-color: #2c3e50;
            --accent-color: #e74c3c;
            --light-color: #ecf0f1;
            --success-color: #2ecc71;
            --warning-color: #f39c12;
            --shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
            --transition: all 0.3s ease;
        }

        body {
            background: linear-gradient(135deg, #f5f7fa 0%, #e4edf5 100%);
            color: #333;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            min-height: 100vh;
            padding-bottom: 40px;
        }

        .header {
            background: linear-gradient(90deg, var(--secondary-color) 0%, var(--primary-color) 100%);
            color: white;
            padding: 20px 0;
            box-shadow: var(--shadow);
            position: sticky;
            top: 0;
            z-index: 100;
        }

        .search-section {
            background: white;
            border-radius: 10px;
            padding: 30px;
            margin: 30px 0;
            box-shadow: var(--shadow);
        }

        .section-title {
            display: flex;
            align-items: center;
            margin-bottom: 25px;
            color: var(--secondary-color);
        }

        .section-title i {
            font-size: 24px;
            margin-right: 10px;
            color: var(--primary-color);
        }

        .search-box {
            display: flex;
            margin-bottom: 25px;
            gap: 15px;
        }

        .search-input {
            flex: 1;
            position: relative;
        }

        .search-input input {
            width: 100%;
            padding: 15px 20px 15px 50px;
            border: 2px solid #e1e5e9;
            border-radius: 8px;
            font-size: 16px;
            transition: var(--transition);
        }

        .search-input input:focus {
            border-color: var(--primary-color);
            box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.2);
            outline: none;
        }

        .search-input i {
            position: absolute;
            left: 20px;
            top: 50%;
            transform: translateY(-50%);
            font-size: 20px;
            color: #95a5a6;
        }

        .btn {
            padding: 15px 30px;
            background: var(--primary-color);
            color: white;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-size: 16px;
            font-weight: 600;
            transition: var(--transition);
            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
        }

        .btn:hover {
            background: #2980b9;
            transform: translateY(-2px);
            box-shadow: 0 6px 15px rgba(52, 152, 219, 0.3);
        }

        .btn-reset {
            background: var(--light-color);
            color: var(--secondary-color);
        }

        .btn-reset:hover {
            background: #d5dbdb;
            box-shadow: 0 6px 15px rgba(189, 195, 199, 0.3);
        }

        .filters {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
            gap: 20px;
            margin-bottom: 25px;
        }

        .filter-group {
            display: flex;
            flex-direction: column;
        }

        .filter-group label {
            margin-bottom: 8px;
            font-weight: 600;
            color: var(--secondary-color);
        }

        .filter-group select {
            padding: 12px 15px;
            border: 2px solid #e1e5e9;
            border-radius: 8px;
            font-size: 16px;
            background: white;
            cursor: pointer;
            transition: var(--transition);
        }

        .filter-group select:focus {
            border-color: var(--primary-color);
            box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.2);
            outline: none;
        }

        .results-section {
            background: white;
            border-radius: 10px;
            padding: 30px;
            box-shadow: var(--shadow);
        }

        .results-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 25px;
        }

        .results-count {
            font-size: 18px;
            font-weight: 600;
            color: var(--secondary-color);
        }

        .results-count span {
            color: var(--primary-color);
        }

        .sort-options {
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .sort-options label {
            font-weight: 600;
            color: var(--secondary-color);
        }

        .results-table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 25px;
        }

        .results-table th {
            background-color: var(--secondary-color);
            color: white;
            text-align: left;
            padding: 15px;
            font-weight: 600;
        }

        .results-table td {
            padding: 15px;
            border-bottom: 1px solid #eee;
        }

        .results-table tr:nth-child(even) {
            background-color: #f9f9f9;
        }

        .results-table tr:hover {
            background-color: #f1f9ff;
        }

        .pagination {
            display: flex;
            justify-content: center;
            gap: 10px;
            margin-top: 30px;
        }

        .pagination button {
            width: 40px;
            height: 40px;
            display: flex;
            align-items: center;
            justify-content: center;
            border: none;
            border-radius: 8px;
            background: white;
            color: var(--secondary-color);
            font-weight: 600;
            cursor: pointer;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
            transition: var(--transition);
        }

        .pagination button:hover {
            background: var(--primary-color);
            color: white;
        }

        .pagination button.active {
            background: var(--primary-color);
            color: white;
        }

        .pagination button:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }

        .no-results {
            text-align: center;
            padding: 50px 20px;
        }

        .no-results i {
            font-size: 60px;
            color: #bdc3c7;
            margin-bottom: 20px;
        }

        .no-results h3 {
            font-size: 24px;
            color: var(--secondary-color);
            margin-bottom: 15px;
        }

        .no-results p {
            color: #7f8c8d;
            max-width: 500px;
            margin: 0 auto;
        }

        .loader {
            display: none;
            text-align: center;
            padding: 40px;
        }

        .spinner {
            width: 40px;
            height: 40px;
            border: 4px solid rgba(0, 0, 0, 0.1);
            border-left-color: var(--primary-color);
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin: 0 auto 20px;
        }

        @keyframes spin {
            to { transform: rotate(360deg); }
        }

        .api-status {
            display: flex;
            align-items: center;
            gap: 8px;
            padding: 8px 15px;
            border-radius: 20px;
            font-size: 14px;
            margin-top: 10px;
            background: rgba(52, 152, 219, 0.1);
            color: var(--primary-color);
        }

        .api-status.error {
            background: rgba(231, 76, 60, 0.1);
            color: var(--accent-color);
        }

        @media (max-width: 768px) {
            .search-box {
                flex-direction: column;
            }

            .results-header {
                flex-direction: column;
                align-items: flex-start;
                gap: 15px;
            }

            .sort-options {
                width: 100%;
                flex-direction: column;
                align-items: flex-start;
            }

            .filters {
                grid-template-columns: 1fr;
            }

            .results-table {
                display: block;
                overflow-x: auto;
            }
        }
    </style>
    <script>
        const API_URL = "{{ api_url }}";
    </script>
</head>
<body>
    <div class="container">
        <section class="search-section">
            <div class="section-title">
                <i class="fas fa-search"></i>
                <h2>商品信息搜索</h2>
            </div>

            <div class="search-box">
                <div class="search-input">
                    <i class="fas fa-search"></i>
                    <input type="text" id="searchInput" placeholder="输入车型、厂商或其他关键词...">
                </div>
                <button class="btn" id="searchBtn"><i class="fas fa-search"></i> 搜索</button>
                <button class="btn btn-reset" id="resetBtn"><i class="fas fa-redo"></i> 重置</button>
            </div>

            <div class="filters">
                <div class="filter-group">
                    <label>年份</label>
                    <select id="yearFilter">
                        <option value="">全部年份</option>

                        <option value="2024">2024年</option>
                        <option value="2023">2023年</option>
                        <option value="2022">2022年</option>
                        <option value="2021">2021年</option>
                        <option value="2020">2020年</option>
                        <option value="2019">2019年</option>
                        <option value="2018">2018年</option>
                        <option value="2017">2017年</option>
                        <option value="2016">2016年</option>
                        <option value="2015">2015年</option>
                        <option value="2014">2014年</option>


                    </select>
                </div>

                <div class="filter-group">
                    <label>月份</label>
                    <select id="monthFilter">
                        <option value="">全部月份</option>
                        <option value="1">1月</option>
                        <option value="2">2月</option>
                        <option value="3">3月</option>
                        <option value="4">4月</option>
                        <option value="5">5月</option>
                        <option value="6">6月</option>
                        <option value="7">7月</option>
                        <option value="8">8月</option>
                        <option value="9">9月</option>
                        <option value="10">10月</option>
                        <option value="11">11月</option>
                        <option value="12">12月</option>
                    </select>
                </div>

                <div class="filter-group">
                    <label>价格范围</label>
                    <select id="priceFilter">
                        <option value="">全部价格</option>
                        <option value="0-15">15万以下</option>
                        <option value="15-30">15-30万</option>
                        <option value="30-50">30-50万</option>
                        <option value="50-100">50-100万</option>
                        <option value="100-999">100万以上</option>
                    </select>
                </div>

                <div class="filter-group">
                    <label>销量范围</label>
                    <select id="salesFilter">
                        <option value="">全部销量</option>
                        <option value="0-100">100台以下</option>
                        <option value="100-500">100-500台</option>
                        <option value="500-1000">500-1000台</option>
                        <option value="1000-5000">1000-5000台</option>
                        <option value="5000-99999">5000台以上</option>
                    </select>
                </div>
            </div>

            <div id="apiStatus" class="api-status">
                <i class="fas fa-circle-notch fa-spin"></i> <span>正在连接数据库...</span>
            </div>
        </section>

        <section class="results-section">
            <div class="results-header">
                <div class="results-count">找到 <span id="resultCount">0</span> 条匹配信息</div>
                <div class="sort-options">
                    <label>排序:</label>
                    <select id="sortSelect">
                        <option value="default">默认排序</option>
                        <option value="price-asc">价格从低到高</option>
                        <option value="price-desc">价格从高到低</option>
                        <option value="sales-asc">销量从低到高</option>
                        <option value="sales-desc">销量从高到低</option>
                    </select>
                </div>
            </div>

            <div class="loader" id="loader">
                <div class="spinner"></div>
                <p>正在从数据库加载数据，请稍候...</p>
            </div>

            <div class="no-results" id="noResults" style="display: none;">
                <i class="fas fa-search"></i>
                <h3>没有找到匹配的商品</h3>
                <p>请尝试其他搜索条件或重置筛选器</p>
            </div>

            <div id="resultsContainer">
                <table class="results-table">
                    <thead>
                        <tr>
                            <th>年份</th>
                            <th>月份</th>
                            <th>排名</th>
                            <th>车型</th>
                            <th>厂商</th>
                            <th>销量</th>
                            <th>售价（万元）</th>
                        </tr>
                    </thead>
                    <tbody id="resultsBody">
                        <!-- 结果将通过JavaScript动态填充 -->
                    </tbody>
                </table>

                <div class="pagination" id="pagination">
                    <!-- 分页将通过JavaScript动态生成 -->
                </div>
            </div>
        </section>
    </div>

    <script>
        // 全局变量
        let currentPage = 1;
        const itemsPerPage = 10;
        let totalItems = 0;
        let currentSearch = '';
        let currentFilters = {};
        let currentSort = 'default';

        // DOM元素
        const searchInput = document.getElementById('searchInput');
        const searchBtn = document.getElementById('searchBtn');
        const resetBtn = document.getElementById('resetBtn');
        const yearFilter = document.getElementById('yearFilter');
        const monthFilter = document.getElementById('monthFilter');
        const priceFilter = document.getElementById('priceFilter');
        const salesFilter = document.getElementById('salesFilter');
        const sortSelect = document.getElementById('sortSelect');
        const resultsBody = document.getElementById('resultsBody');
        const pagination = document.getElementById('pagination');
        const loader = document.getElementById('loader');
        const noResults = document.getElementById('noResults');
        const resultCount = document.getElementById('resultCount');
        const resultsContainer = document.getElementById('resultsContainer');
        const apiStatus = document.getElementById('apiStatus');

        // 初始化页面
        document.addEventListener('DOMContentLoaded', () => {
            // 添加事件监听器
            searchBtn.addEventListener('click', handleSearch);
            resetBtn.addEventListener('click', resetFilters);

            // 筛选器变更时重新加载数据
            [yearFilter, monthFilter, priceFilter, salesFilter, sortSelect].forEach(filter => {
                filter.addEventListener('change', () => {
                    currentPage = 1;
                    fetchData();
                });
            });

            // 回车键搜索
            searchInput.addEventListener('keyup', (e) => {
                if (e.key === 'Enter') {
                    handleSearch();
                }
            });

            // 初始加载数据
            fetchData();
        });

        function handleSearch() {
            currentSearch = searchInput.value;
            currentPage = 1;
            fetchData();
        }

        // 重置筛选器
        function resetFilters() {
            searchInput.value = '';
            yearFilter.value = '';
            monthFilter.value = '';
            priceFilter.value = '';
            salesFilter.value = '';
            sortSelect.value = 'default';

            currentSearch = '';
            currentFilters = {};
            currentSort = 'default';
            currentPage = 1;

            fetchData();
        }

        // 从API获取数据
        function fetchData() {
            // 显示加载状态
            loader.style.display = 'block';
            noResults.style.display = 'none';
            resultsContainer.style.display = 'none';

            // 更新API状态
            apiStatus.innerHTML = '<i class="fas fa-circle-notch fa-spin"></i> <span>正在查询数据库...</span>';

            // 构建查询参数
            const params = new URLSearchParams();
            params.append('search', currentSearch);
            params.append('page', currentPage);
            params.append('per_page', itemsPerPage);

            // 添加筛选条件
            if (yearFilter.value) params.append('year', yearFilter.value);
            if (monthFilter.value) params.append('month', monthFilter.value);
            if (priceFilter.value) params.append('price_range', priceFilter.value);
            if (salesFilter.value) params.append('sales_range', salesFilter.value);
            if (sortSelect.value !== 'default') params.append('sort', sortSelect.value);

            // 记录请求URL
            console.log(`API请求: ${API_URL}?${params.toString()}`);

            // 调用后端API
            fetch(`${API_URL}?${params.toString()}`)
                .then(response => {
                    if (!response.ok) {
                        // 尝试解析错误信息
                        return response.json().then(errData => {
                            throw new Error(errData.error || 'API请求失败');
                        }).catch(() => {
                            throw new Error(`HTTP错误: ${response.status} ${response.statusText}`);
                        });
                    }
                    return response.json();
                })
                .then(data => {
                    if (data.error) {
                        throw new Error(data.error);
                    }

                    // 更新状态显示
                    apiStatus.innerHTML = '<i class="fas fa-check-circle"></i> <span>查询成功</span>';

                    // 处理响应数据
                    totalItems = data.total;
                    resultCount.textContent = totalItems;

                    if (totalItems > 0) {
                        renderResults(data.data);
                        renderPagination();
                        resultsContainer.style.display = 'block';
                        noResults.style.display = 'none';
                    } else {
                        resultsContainer.style.display = 'none';
                        noResults.style.display = 'block';
                    }

                    loader.style.display = 'none';
                })
                .catch(error => {
                    console.error('获取数据失败:', error);
                    loader.style.display = 'none';
                    const errorMsg = error.message || '未知错误';
                    apiStatus.innerHTML = `<i class="fas fa-exclamation-triangle"></i> <span>查询失败: ${errorMsg}</span>`;
                    apiStatus.classList.add('error');

                    // 显示错误信息
                    const errorDiv = document.createElement('div');
                    errorDiv.className = 'alert alert-danger mt-3';
                    errorDiv.innerHTML = `<strong>错误:</strong> ${errorMsg}`;
                    resultsContainer.parentNode.insertBefore(errorDiv, resultsContainer);
                });
        }

        // 渲染结果
        function renderResults(products) {
            resultsBody.innerHTML = '';

            products.forEach(product => {
                const row = document.createElement('tr');

                row.innerHTML = `
                    <td>${product.year}</td>
                    <td>${product.month}月</td>
                    <td>${product.ranks}</td>
                    <td>${product.model}</td>
                    <td>${product.manufacturer}</td>
                    <td>${product.sales.toLocaleString()}</td>
                    <td>¥${parseFloat(product.price).toFixed(2)}</td>
                `;

                resultsBody.appendChild(row);
            });
        }

        // 渲染分页控件
        function renderPagination() {
            pagination.innerHTML = '';

            const totalPages = Math.ceil(totalItems / itemsPerPage);

            if (totalPages <= 1) return;

            // 上一页按钮
            const prevButton = document.createElement('button');
            prevButton.innerHTML = '<i class="fas fa-chevron-left"></i>';
            prevButton.disabled = currentPage === 1;
            prevButton.addEventListener('click', () => {
                if (currentPage > 1) {
                    currentPage--;
                    fetchData();
                    window.scrollTo({ top: 0, behavior: 'smooth' });
                }
            });
            pagination.appendChild(prevButton);

            // 页码按钮
            const startPage = Math.max(1, currentPage - 2);
            const endPage = Math.min(totalPages, currentPage + 2);

            for (let i = startPage; i <= endPage; i++) {
                const pageButton = document.createElement('button');
                pageButton.textContent = i;
                pageButton.className = currentPage === i ? 'active' : '';

                pageButton.addEventListener('click', () => {
                    currentPage = i;
                    fetchData();
                    window.scrollTo({ top: 0, behavior: 'smooth' });
                });

                pagination.appendChild(pageButton);
            }

            // 下一页按钮
            const nextButton = document.createElement('button');
            nextButton.innerHTML = '<i class="fas fa-chevron-right"></i>';
            nextButton.disabled = currentPage === totalPages;
            nextButton.addEventListener('click', () => {
                if (currentPage < totalPages) {
                    currentPage++;
                    fetchData();
                    window.scrollTo({ top: 0, behavior: 'smooth' });
                }
            });
            pagination.appendChild(nextButton);
        }
    </script>
</body>
</html>